<?php

class Reportes_FallasController extends Zend_Controller_Action
{

    /**
     * 
     * @var Zend_Auth_Storage_Interface
     */
    private $_user_info;
    /**
     * 
     * @var Zwei_Admin_Acl
     */
    private $_acl;
    /**
     * 
     * @var string
     */
    private $_page;

    public function init()
    {
        $this->_helper->layout()->disableLayout();
        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_user_info = Zend_Auth::getInstance()->getStorage()->read();
            $this->_acl = new Zwei_Admin_Acl($this->_user_info->user_name);
            $this->_page = "reportes/fallas";
        } else {
            $this->_redirect('index/login');
        }
    }

    public function indexAction()
    {
        //if (!$this->_acl->isUserAllowed($this->_page)) exit("<p>Acceso denegado a $this->_page</p>"); 
        include_once ROOT_DIR."/libs/funciones.php";
        include_once ROOT_DIR."/classes/reportes-class.php";
        include_once ROOT_DIR."/classes/promociones-class.php";



        error_reporting(E_ALL);

        echo "<script src='".BASE_URL."js/funciones.js'></script>";

        # Titulo
        echo "<h2>Reporte de Fallas</h2>";

        $form = new HTML_Form(BASE_URL.'reportes/fallas','post','myform','ifrm_process');
        echo $form->returnStart()."\n";


        $tableAttrs = array('border' => "0",
                    'cellspacing' => "0",
                    'align' => "center",
                    'class' => "",
            'width' => "20%");

        $table = new HTML_Table($tableAttrs);
        $titleStyle = array('colspan' => "5");
        $blankStyle = array('colspan' => "5");
        $rowStyle   = array('align' => "left");
        $fila=0;

        //Buscar por Operacion
        $row = array("<p CLASS=textoAzul>Operacion</p>",
        $form->returnSelect('operacion', array('req_comp_promo' => 'Compras', 'req_elim_promo' => 'Elimaciones', 'req_cons_saldo' => 'Consultas de saldo', 'provisioning' => 'Provisioning'),
        @$_REQUEST["operacion"],1, 'Seleccione... ',false, " dojoType=\"dijit.form.FilteringSelect\" "),
         ""  );
        $table->addRow($row,$rowStyle);
        $table->updateCellAttributes($fila, 1, array('valign' => "center"));


        $fecha_ini = $form->returnText("fecha_ini",@$_REQUEST["fecha_ini"], 12, 12," dojoType=\"dijit.form.DateTextBox\" ");
        $row = array("<p CLASS=textoAzul>Fecha&nbsp;inicio</p>", $fecha_ini);
        $table->addRow($row, $rowStyle);
        $table->updateCellAttributes($fila, 2, array('valign' => "center"));


        $fecha_fin    = $form->returnText("fecha_fin",@$_REQUEST["fecha_fin"],12,12," dojoType=\"dijit.form.DateTextBox\" ");

        $row = array("<p CLASS=textoAzul>Fecha&nbsp;fin</p>", $fecha_fin);
        $table->addRow($row, $rowStyle);
        $table->updateCellAttributes($fila, 3, array('valign' => "center"));


        $row = array("", $form->returnSubmit("Consultar","consultar","class='boton2' onClick='return validaFallas();'"));
        $table->addRow($row, $rowStyle);
        $table->updateCellAttributes($fila, 4, array('valign' => "center"));


        $fila++;
        $table->display();
        echo "<br>";

        if( @$_REQUEST["consultar"] == "Consultar")
        {
            $requests = "?";
            foreach ($_REQUEST as $i => $v) {
                $requests .= "&$i=$v";
            }

            if (!isset($_REQUEST['norepost'])) {

                echo "<script>window.parent.cargarPanelCentral('reportes/fallas$requests&norepost=1'); </script>";
            }


            $fallas = new REPORTES('', '', '', $_REQUEST["fecha_ini"], $_REQUEST["fecha_fin"],$_REQUEST["operacion"],0);
            $fallas->get_fallas();

            if( count($fallas->elementos) != 0)
            {
                #--- Parametros generales para las tablas usuarios y campaanas
                $tableUsuCamp = array('border' => "0",
                          'cellspacing' => "0",
                          'align' => "center",
                          'class' => "borde3",
                          'width' => "35%");

                $titleStyle = array('align' => "left");
                $blankStyle = array('align' => "left");
                $rowStyle   = array('align' => "left");
                #---


                $table = new HTML_Table($tableUsuCamp);
                if (array_key_exists("msg", $_REQUEST))
                $msg = $_REQUEST["msg"];
                else
                $msg = "&nbsp;";

                $msgStyle = array('align' => "center", 'bgcolor' => $blankColor);
                $msgRow = array("<font class='textoAzul'>$msg</font>");

                $row = array(
                 "<label class=SUBT>Modulo</label>",
         "<label class=SUBT>Exito</label>",
         "<label class=SUBT>Error</label>",
         "<label class=SUBT>% de errores</label>"
         );

         $table->addRow($row,$titleStyle);

         $fila = 0;
         $i = 1;

         $fallas->getTotalOperacion();
         $totalFallas = 0;

         $totalFallasXML = 0;
         $totalFallasSMSC = 0;
         $totalFallasSOAP = 0;
         $totalFallasSISCEL = 0;

         $totalExito = 0;
         $totalExitoXML = 0;
         $totalExitoSMSC = 0;
         $totalExitoSOAP = 0;
         $totalExitoSISCEL = 0;

         $totalSinSaldo = 0;

         $table->updateCellAttributes($fila,0,array('width' => "5%"));
         $table->updateCellAttributes($fila,1,array('width' => "10%"));
         $table->updateCellAttributes($fila,2,array('width' => "10%"));
         $table->updateCellAttributes($fila,3,array('width' => "10%"));

         $fallas->get_exito();
         $arr=array();

         foreach ($fallas->exitos as $key => $value)
         {

             $totalExito = $totalExito + $value[1];

             //                 if( $value[0] == "XML" ||$value[0] == "xml" )
             //                         $totalExitoXML = $value[1];
             //                 else if( $value[0] == "SMSC" )
             //                         $totalExitoSMSC = $value[1];
             //                 else if( $value[0] == "SOAP" )
             //                         $totalExitoSOAP = $value[1];
             //                 else if( $value[0] == "SISCEL"|| $value[0] == "siscel" )
             //          $totalExitoSISCEL = $value[1];

         }

         foreach ($fallas->elementos as $key => $value)
         {
             $exito = 0;
             $porcentaje = 0;

             if( $_REQUEST["operacion"] == "req_cons_saldo" )
             {
                 if( $value[1] == 7)
                 $totalSinSaldo = $totalSinSaldo + $value[2];
                 else
                 $totalFallas = $totalFallas + $value[2];
             }
             else
             $totalFallas = $totalFallas + $value[2];


         }
         $arr['Transacciones exitosas']=$totalExito;
         $arr['Transacciones con error']=$totalFallas;

         if( $_REQUEST["operacion"] == "req_cons_saldo" )
         $arr['Sin saldo']=$totalSinSaldo;

         echo "<br>";

         if( $_REQUEST["operacion"] == "req_comp_promo" )
         $aux = "Compras";
         else if( $_REQUEST["operacion"] == "req_elim_promo" )
         $aux = "Eliminaciones";
         else if( $_REQUEST["operacion"] == "req_cons_saldo" )
         $aux = "Consulta de Saldo";


         $ancho=1000;
         $title="Reporte de Fallas";
         $colores=array('green', 'blue', 'yellow', 'red');

         $Graph =& Image_Graph::factory('graph', array($ancho/2, $ancho/3));

         $Graph->add(
         Image_Graph::vertical(
         Image_Graph::factory('title', array($title, 12)),
         Image_Graph::horizontal(
         $Plotarea = Image_Graph::factory('plotarea'),
         $Legend   = Image_Graph::factory('legend'),
         60
         ),
         20
         )
         );
         $Legend->setPlotarea($Plotarea);

         ####################################
         # se agregan los puntos al grafico #
         ####################################
         $dataportal=& Image_Graph::factory('dataset');

         ksort ($arr);
         //asort( $arr );
         foreach ($arr as $index => $data)
         {
             //       echo "$index $data<br>";
             $dataportal->addPoint("$index ($data)", $data);

         }

         $plots =& $Plotarea->addNew('pie', array(&$dataportal));
         $Plotarea->hideAxis();

         // create a Y data value marker
         $Marker =& $plots->addNew('Image_Graph_Marker_Value', IMAGE_GRAPH_PCT_Y_TOTAL);
         // create a pin-point marker type
         $PointingMarker =& $plots->addNew('Image_Graph_Marker_Pointing_Angular', array(20, &$Marker));
         // and use the marker on the 1st plot
         $plots->setMarker($PointingMarker);

         // format value marker labels as percentage values
         $Marker->setDataPreprocessor(Image_Graph::factory('Image_Graph_DataPreprocessor_Function', 'miFormatFunction'));

         ###################################################################################
         $plots->Radius = 2;

         $FillArray =& Image_Graph::factory('Image_Graph_Fill_Array');

         $plots->setFillStyle($FillArray);
         $col=0;
         $FillArray->addNew('gradient', array(IMAGE_GRAPH_GRAD_RADIAL, 'white', $colores[0]));
         $FillArray->addNew('gradient', array(IMAGE_GRAPH_GRAD_RADIAL, 'white', $colores[1]));
         $FillArray->addNew('gradient', array(IMAGE_GRAPH_GRAD_RADIAL, 'white', $colores[2]));
         $FillArray->addNew('gradient', array(IMAGE_GRAPH_GRAD_RADIAL, 'white', $colores[3]));
         //$FillArray->addNew('gradient', array(IMAGE_GRAPH_GRAD_RADIAL, 'white', $colores[4]));

         $col++;
         $plots->explode(4);

         ########################
         # finalmente se dibuja #
         ########################

         
         $image = "reporte_fallas_" . time() . ".jpg";   
         $filename1 = ROOT_DIR . "/public/pear_ex/$image";
         $publicFilename1 = BASE_URL . "/pear_ex/$image";         
         $Graph->done( array('filename' => "$filename1") );

         echo "<table border=1 align=center>";
         echo "<tr><td><img src='$publicFilename1'></tr></td>";
         echo "</table><br>";

         echo $form->returnEnd()."\n";
            }
            else
            echo "<br><br><br><p class=SUBT align=center>No existen registros</p>";
        }
    }
}

//funciones legacy que son usadas en /Image/Graph/DataPreprocessor/Function.php
    function redondear_dos_decimal($valor) {
        $float_redondeado=round($valor * 100) / 100;
        return $float_redondeado;
    }
    
    function miFormatFunction($numero){
        $str= sprintf("%0.2f%%",  $numero);
        return $str;
    }

